import * as path from 'path';
import * as vscode from 'vscode';
import * as child_process from 'child_process';

const net = require('net');
var express = require('express');
var app = express();
var p = 0;
var ser: { close: () => void; } | null = null;

function startServe(args: String) {

    var folders = vscode.workspace.workspaceFolders;
    if (!folders) {
        return;
    }
    var paths = folders[0].uri.fsPath;
    //Node 版本
    if (args === '0') {
        if (ser === null) {
            app.use(express.static(path.join(paths)));
            portIsOccupied(9527);
            vscode.window.showInformationMessage("启动成功");
        } else {
            vscode.window.showWarningMessage("已经启动过了");
        }
    } else if (args === '1') {
        if (ser !== null) {
            ser.close();
            ser = null;
            vscode.window.showInformationMessage("关闭成功");
        } else {
            vscode.window.showWarningMessage("还未启动");
        }
    } else {
        if (ser !== null) {
            ser.close();
        }
        app.use(express.static(path.join(paths)));
        portIsOccupied(9527);
        vscode.window.showInformationMessage("重启成功！");
    }
}
function portIsOccupied(port: any) {
    // 创建服务并监听该端口
    var server = net.createServer().listen(port);

    server.on('listening', function () { // 执行这块代码说明端口未被占用
        server.close(); // 关闭服务
        p = port;
        ser = app.listen(port);
        start();
        console.log('The port【' + port + '】 is available.'); // 控制台输出信息
    });

    server.on('error', function (err: any) {
        if (err.code === 'EADDRINUSE') { // 端口已经被使用
            port = port + 1;
            p = port;
            portIsOccupied(port);
            console.log('The port【' + port + '】 is occupied, please change other port.');
        }
    });

}


function start() {
    switch (process.platform) {
        case "darwin":
            child_process.exec('open http://127.0.0.1:' + p + '/static');
        case "win32":
            child_process.exec('start http://127.0.0.1:' + p + '/static');
        default:
            child_process.exec('open http://127.0.0.1:' + p + '/static');
    }
}

export default {
    startServe: startServe
};